package com.soos.service.impl;

import com.soos.dto.Result;
import com.soos.entity.Voucher;
import com.soos.entity.VoucherOrder;
import com.soos.mapper.VoucherOrderMapper;
import com.soos.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.soos.service.IVoucherService;
import com.soos.utils.RedisWorker;
import com.soos.utils.UserHolder;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private IVoucherService iVoucherService;
    @Resource
    private RedisWorker redisWorker;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;

    /**
     * 实现秒杀下单功能
     * @param voucherId
     * @return
     */
    @Override
    public Result seckillVoucher(Long voucherId) {
        //查询优惠券
        Voucher voucher = iVoucherService.getById(voucherId);
        //1.判断秒杀时间有没有开始
        if(voucher.getBeginTime().isBefore(LocalDateTime.now())) {
            return Result.fail("秒杀尚未开始");
        }
        //2.判断秒杀时间有没有结束
        if(voucher.getEndTime().isAfter(LocalDateTime.now())) {
            return Result.fail("秒杀已经结束");
        }
        //3.库存是否充足
        if(voucher.getStock() <=0) {
            return Result.fail("库存不足");
        }
        //4.扣减库存->使用乐观锁解决超卖问题
        //1.成功率太低
        //        boolean isSuccess = update().setSql("stock=stock-1")
        //       .eq("voucher_id", voucherId).eq("stock",voucher.getStock())
        //        .update();
        Long userId = UserHolder.getUser().getId();
        //创建锁对象
        RLock lock = redissonClient.getLock("order:");
        //SimpleRedisLock lock = new SimpleRedisLock("order:",stringRedisTemplate);
        //尝试获取锁
        boolean isSuccess = lock.tryLock();
        if(!isSuccess) {
            return Result.fail("不允许重复下单");
        }
        try {
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId);
        }finally {
            //释放锁
            lock.unlock();
        }
    }

    @Transactional
    public  Result createVoucherOrder(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        //解决一人一单的问题
        Integer count = query().eq("user_id", userId).eq("vouvher_id", voucherId).count();
        if (count > 0) {
            return Result.fail("用户已经下过单了");
        }
        //扣减库存
        boolean isSuccess = update().setSql("stock=stock-1")
                .eq("voucher_id", voucherId).gt("stock", 0)
                .update();
        if (!isSuccess) {
            return Result.fail("库存不足");
        }
        //5.下订单
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setVoucherId(voucherId);
        long orderId = redisWorker.nextId("order");
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        return Result.ok(orderId);
    }
}